// import Vue from 'vue'
// import Vuex from 'vuex'

import {
  setStore,
  getStore
} from '@/config/mUtils'
import {
  buildLoginVerifyInfo,
  buildRegisteVerifyInfo
} from '@/utils/loginUtils'

import manage from './modules/manage'

import {
  getToken,
  login,
  register
} from '@/api/login'

import {
  siteName
} from '@/api/site'
import {
  configAll
} from '@/api/admin'
import {
  getGiftList
} from '@/api/gift'
import {
  getUserAccount,
  getUserInfo
} from '@/api/myinfo'
import {
  level,
  deleteCookie
} from '@/utils/cookie'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

const state = {
  site: {},
  configs: {},
  gifts: [],
  pending: [],
  userInfo: {},
  userLevel: {},
  role: 0
}

const getters = {
  getConfigByKey: (state) => (key) => {
    return key in state.configs ? state.configs[key] : ''
  },
  namespace: (state) => {
    return 'namespaceDesc' in state.site ? state.site['namespace'] : ''
  },
  namespaceDesc: (state) => {
    return 'namespaceDesc' in state.site ? state.site['namespaceDesc'] : ''
  }
}

const mutations = {
  saveSite: (state, site) => {
    state.site = site
    setStore('site', site)
  },
  saveConfigs: (state, configs) => {
    state.configs = configs
    setStore('configs', configs)
  },
  saveGifts: (state, gifts) => {
    state.gifts = gifts
    setStore('gifts', gifts)

    // let left = this.gifts.length % 4
    state.pending = [...Array(100)].map((_, index) => `${index}-`)
  },
  saveUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  saveUserLevel: (state, userLevel) => {
    state.userLevel = userLevel
  },
  updateRole: (state) => {
    state.role = level()
  }
}

const actions = {
  login: async ({
    commit
  }, userInfo) => {
    let tokenInfo = {
      applyType: 'TYPE_LOGIN'
    }
    let result = await getToken(tokenInfo)

    if (result.status === 200) {
      let encryptInfo = result.data.data
      let verifyInfo = buildLoginVerifyInfo(userInfo, encryptInfo)

      const res = await login(verifyInfo)
      if (res.status === 200 && res.data.code === 200) {
        // let data = res.data
        // window.userId = data.data.id
        commit('updateRole')
      } else {
        throw new Error('login failed!')
      }
    }
  },
  logout: async ({
    commit
  }) => {
    deleteCookie()
    commit('updateRole')
  },
  register: async ({
    commit
  }, userInfo) => {
    let tokenInfo = {
      telNum: userInfo.phoneNumber,
      applyType: 'TYPE_REGISTER'
    }
    let result = await getToken(tokenInfo)

    if (result.status === 200) {
      let encryptInfo = result.data.data
      let verifyInfo = buildRegisteVerifyInfo(userInfo, encryptInfo)

      const res = await register(verifyInfo)
      if (res.status === 200 && res.data.code === 200) {
        // let data = res.data
        // window.userId = data.data.id
      } else {
        throw new Error(res.message)
      }
    }
  },
  init: async ({
    dispatch,
    commit
  }) => {
    commit('saveSite', JSON.parse(getStore('site')))
    commit('saveConfigs', JSON.parse(getStore('configs')))
    commit('saveGifts', JSON.parse(getStore('gifts')))

    dispatch('getSiteName')
    commit('updateRole')
    // dispatch('getAllConfig')
    // dispatch('getGiftList')
  },
  getSiteName: async ({
    commit
  }) => {
    try {
      const result = await siteName()
      if (result.status === 200 && result.data.code === 200) {
        let data = result.data
        commit('saveSite', data.data)
      }
    } catch (err) {
      console.log(err)
    }
  },
  getAllConfig: async ({
    commit
  }) => {
    try {
      const result = await configAll({
        'configAccess': 'FRONT'
      })
      if (result.status === 200 && result.data.code === 200) {
        let configs = Object.assign({}, ...result.data.data.map(e => {
          return {
            [e['configKey']]: e['configValue']
          }
        }))

        commit('saveConfigs', configs)
      }
    } catch (err) {
      console.log(err)
    }
  },
  getGiftList: async ({
    commit
  }) => {
    try {
      let result = await getGiftList(false)
      if (result.status === 200 && result.data.code === 200) {
        let gifts = result.data.data.filter((e, i, a) => {
          return e.status === 'ENABLE' && e.resourceDesc.search(/^API_/) === -1
        })
        commit('saveGifts', gifts)
      } else {
        throw new Error('获取数据失败')
      }
    } catch (err) {
      // this.$message.error('获取数据失败')
      console.log('获取数据失败', err)
    }
  },
  getUserAccount: async ({
    commit
  }) => {
    try {
      const result = await getUserAccount()
      if (result.status === 200 && result.data.code === 200) {
        let data = result.data
        commit('saveUserInfo', data.data)
      }
    } catch (err) {
      console.log(err)
    }
  },
  getUserInfo: async ({
    commit
  }) => {
    try {
      const result = await getUserInfo()
      if (result.status === 200 && result.data.code === 200) {
        let info = result.data
        commit('saveUserLevel', info.data)
      }
    } catch (err) {
      console.log(err)
    }
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters,
  strict: debug,
  modules: {
    manage
  }
})
